package model

import (
	"hertz/demo/biz/util"
	"time"

	"gorm.io/gorm"
)

// 更新用户
func UpdateUser(db *gorm.DB, user *User) error {
	user.CreatedAt = time.Time{}
	user.UpdatedAt = time.Time{}
	if user.Password != "" {
		hash, err := util.HashPassword(user.Password)
		if err != nil {
			return err
		}
		user.Password = hash
	}
	return db.Model(user).Updates(user).Error
}

// 禁用某个用户
func DisableUser(db *gorm.DB, id uint) error {
	return db.Model(&User{ID: id}).Update("disable", true).Error
}

// 启用某个用户
func EnableUser(db *gorm.DB, id uint) error {
	return db.Model(&User{ID: id}).Update("disable", false).Error
}

func ResetUserPassword(db *gorm.DB, id uint, password string) error {
	hash, err := util.HashPassword(password)
	if err != nil {
		return err
	}

	return db.Model(&User{ID: id}).Update("password", hash).Error
}

// 用户是否正常启用
func IsUserEnable(db *gorm.DB, id uint) (bool, error) {
	user, err := FindUser(db, id)
	if err != nil {
		return false, err
	}
	return !user.Disable, nil
}

// 用户是否已经被禁用
func IsUserDisable(db *gorm.DB, id uint) (bool, error) {
	user, err := FindUser(db, id)
	if err != nil {
		return false, err
	}
	return user.Disable, nil
}

func AddUser(db *gorm.DB, user *User) error {
	hash, err := util.HashPassword(user.Password)
	if err != nil {
		return err
	}
	user.Password = hash
	return db.Create(user).Error
}

// 查找用户
func FindUser(db *gorm.DB, userId uint) (*User, error) {
	user := &User{
		ID: userId,
	}
	if err := db.Take(&user).Error; err != nil {
		return nil, err
	}
	return user, nil
}

// 查询某个用户是否是管理员
func IsAdmin(db *gorm.DB, userId uint) (bool, error) {
	user, err := FindUser(db, userId)
	if err != nil {
		return false, err
	}
	return user.IsAdmin, nil
}

// 查询所有的用户
func ListUser(db *gorm.DB) ([]User, error) {
	users := []User{}
	if err := db.Find(&users).Error; err != nil {
		return nil, err
	}
	for _, user := range users {
		user.Password = ""
	}
	return users, nil
}
